package photobox.manage

import grails.transaction.Transactional
import grails.converters.JSON
import grails.validation.ValidationException
import photobox.account.Address
import photobox.account.Member
import photobox.account.Notice
import photobox.account.Region
import photobox.account.User
import photobox.exception.NotFoundException
import photobox.order.Order
import photobox.order.OrderItem
import photobox.photo.Photo
import photobox.photo.PhotoFrame
import photobox.photo.PhotoPaper
import photobox.photo.PhotoSize
import photobox.utils.HQLUtils

@Transactional
class OrderService {

    def saveOrder(params, session) {
        def order = new Order()
        order.orderStatus = Order.ORDER_STATUS_COMMIT  //订单已提交,用户不能再修改,并等待付款
        order.cancelStatus = Order.CANCEL_STATUS_NORMAL  //订单未取消

        order.user = User.get(session.userId)
        order.isInvoice = 0   //是否开发票
        order.invoiceType = 1//  invoiceType //发票类型
        order.invoiceTitle = ''//  invoiceTitle //发票title
        order.invoiceSort = 1//  invoiceSort //发票种类


        //PhotoFrame  photoFrame      //镜框
        //PhotoPaper  photoPaper      //纸张
       //PhotoSize  photoSize        //尺寸

        /*
         * 为了避免订单下订单后变更价格产生冲突,这里保存当时的价格,并以此为准
         */
        //Float  framePrice       //相框价格
       // Float  paperPrice       //纸张价格
       // Float  photoPrice       //图片价格

       // //Integer adornType //装裱方式
       // Integer number  //数量
        def totalPrice = 0
        session.orderItems.each{
            def orderItem = new OrderItem()
            totalPrice += it.eachPrice
            orderItem.photoFrame =  PhotoFrame.get(it.photoFrame)
            orderItem.photoPaper = PhotoPaper.get(it.photoPaper)
            orderItem.photoSize = PhotoSize.get(it.photoSize)

            orderItem.framePrice = it.framePrice
            orderItem.paperPrice = it.paperPrice
            orderItem.photoPrice = it.price
            orderItem.packingPrice = it.packingPrice
            orderItem.number = it.number
            orderItem.photo = Photo.get(it.photoId)
            order.addToItems(orderItem)
        }

        order.totalPrice = totalPrice
        if (!order.save()) {
            return 0
        }else{
            return order
        }
    }
    def updateOrderStatus(orderId, status) {
        def order = Order.get(orderId)
        order.orderStatus = status
        if (!order.save()) {
            return 0
        }else{
            return order.id
        }
    }
    def mngOrderList(searchParam, pageParam, sortParam) {
        def hql = ""
        hql += " from Order A where 1=1 "
        def params = [:]
        if (searchParam.id) {
            hql += " and " + HQLUtils.whereCondition("A.id", searchParam.id.opt, "id")
            params.id = searchParam.id.data
        }
        if (searchParam.totalPrice) {
            hql += " and " + HQLUtils.whereCondition("A.totalPrice", searchParam.totalPrice.opt, "totalPrice")
            params.totalPrice = searchParam.totalPrice.data
        }
        if (searchParam.dateCreated) {
            hql += " and " + HQLUtils.whereCondition("A.dateCreated", searchParam.nickName.opt, "dateCreated")
            params.dateCreated = searchParam.nickName.dateCreated
        }
        if (searchParam.orderStatus) {
            hql += " and " + HQLUtils.whereCondition("A.orderStatus", searchParam.nickName.opt, "orderStatus")
            params.orderStatus = searchParam.nickName.orderStatus
        }

        def sortHql = ""
        if (sortParam.sort) {
            sortHql = " order by A.${sortParam.sort} ${sortParam.order} "
        }
        def results = Order.executeQuery("select distinct A " + hql + sortHql, params,
                [max: pageParam.pageSize, offset: pageParam.offset])
        def count = Order.executeQuery("select count(distinct A.id) " + hql, params)
        return [rs:results, total:count[0]]
    }
    def list_deliver(searchParam, pageParam, sortParam) {
        def hql = ""
        hql += " from Order A where 1=1 and orderStatus>=40 "
        def params = [:]
        if (searchParam.id) {
            hql += " and " + HQLUtils.whereCondition("A.id", searchParam.id.opt, "id")
            params.id = searchParam.id.data
        }
        if (searchParam.totalPrice) {
            hql += " and " + HQLUtils.whereCondition("A.totalPrice", searchParam.totalPrice.opt, "totalPrice")
            params.totalPrice = searchParam.totalPrice.data
        }
        if (searchParam.dateCreated) {
            hql += " and " + HQLUtils.whereCondition("A.dateCreated", searchParam.dateCreated.opt, "dateCreated")
            params.dateCreated = searchParam.dateCreated.data
        }
        if (searchParam.orderStatus) {
            hql += " and " + HQLUtils.whereCondition("A.orderStatus", searchParam.orderStatus.opt, "orderStatus")
            params.orderStatus = searchParam.orderStatus.data
        }

        def sortHql = ""
        if (sortParam.sort) {
            sortHql = " order by A.${sortParam.sort} ${sortParam.order} "
        }
        def results = Order.executeQuery("select distinct A " + hql + sortHql, params,
                [max: pageParam.pageSize, offset: pageParam.offset])
        def count = Order.executeQuery("select count(distinct A.id) " + hql, params)
        return [rs:results, total:count[0]]
    }

    def order_deliver(searchParam, pageParam, sortParam) {
        def hql = ""
        hql += " from Order A where 1=1 "
        def params = [:]
        if (searchParam.id) {
            hql += " and " + HQLUtils.whereCondition("A.id", searchParam.id.opt, "id")
            params.id = searchParam.id.data
        }
        if (searchParam.totalPrice) {
            hql += " and " + HQLUtils.whereCondition("A.totalPrice", searchParam.totalPrice.opt, "totalPrice")
            params.totalPrice = searchParam.totalPrice.data
        }
        if (searchParam.dateCreated) {
            hql += " and " + HQLUtils.whereCondition("A.dateCreated", searchParam.dateCreated.opt, "dateCreated")
            params.dateCreated = searchParam.dateCreated.data
        }
        if (searchParam.orderStatus) {
            hql += " and " + HQLUtils.whereCondition("A.orderStatus", searchParam.orderStatus.opt, "orderStatus=50")
            params.orderStatus = searchParam.orderStatus.data
        }

        def sortHql = ""
        if (sortParam.sort) {
            sortHql = " order by A.${sortParam.sort} ${sortParam.order} "
        }
        def results = Order.executeQuery("select distinct A " + hql + sortHql, params,
                [max: pageParam.pageSize, offset: pageParam.offset])
        def count = Order.executeQuery("select count(distinct A.id) " + hql, params)
        return [rs:results, total:count[0]]
    }

    def sendMessage(userId,message){
        def notice = new Notice()
          notice.message = message
          notice.user =  User.get(userId)
          notice.isRead =notice.isRead_NO
          notice.readTime = new Date()
        if(!notice.save()){
            println(notice.errors)
        }
    }
    def updatePhotoSaleNum(orderId){
        def order = Order.get(orderId)
        order.items.each{
            def photo = Photo.get(it.photo.id)
            photo.saleNum = photo.saleNum + it.number
            if(!photo.save()){
                println(photo.errors)
            }
        }
    }
}
